import { Component } from "react";
import { View } from "@tarojs/components";
import { createInnerAudioContext } from "@tarojs/taro";
import { AtList, AtListItem, AtNoticebar, AtSearchBar } from "taro-ui";
import { getHot, getUrl, getSearch } from "@/api/music";
import Loading from "@/components/Loading";
import "./index.less";

const innerAudioContext = createInnerAudioContext();
innerAudioContext.autoplay = true;

export default class Index extends Component {
  state: any = {
    listData: [],
    active: { index: undefined, name: "", artist: "", src: "" },
    value: "",
    isSearch: false,
  };

  componentDidMount() {
    const { listData, active } = this.state;
    this.getHotData();

    innerAudioContext.onEnded(async () => {
      const nextRes = await getUrl({
        id: listData[active.index + 1].id,
      });
      innerAudioContext.src = nextRes.data[0].url;
    });
  }

  getHotData = () => {
    getHot({ id: 3778678 }).then((res) => {
      this.setState({ listData: res.playlist.tracks });
    });
  };

  onSearch = async () => {
    this.setState({
      listData: [],
    });
    const res = await getSearch({ keywords: this.state.value });

    this.setState({
      listData: res.result.songs,
      isSearch: true,
      active: { index: undefined, name: "", artist: "", src: "" },
    });
  };

  getArtist = (data) => {
    if (data.length < 2) return data[0].name;

    return data.reduce((item, str) => {
      return str.name + ` / ${item.name}`;
    });
  };

  render() {
    const { listData, active, isSearch } = this.state;

    return (
      <View className="music">
        <AtSearchBar
          value={this.state.value}
          onChange={(value) => {
            this.setState({
              value,
            });
          }}
          onClear={() => {
            this.setState({ listData: [], value: "" });
          }}
          onActionClick={this.onSearch}
          onConfirm={this.onSearch}
        />
        <AtNoticebar marquee icon="volume-plus">
          正在播放【{active.name} --- {active.artist}】
        </AtNoticebar>

        <View className="title">
          {isSearch ? `共${listData.length}条搜索结果` : "推荐曲目"}
          {isSearch && (
            <View
              className="visibleHot"
              onClick={() => {
                this.setState({ isSearch: false, listData: [] });
                this.getHotData();
              }}
            >
              查看推荐曲目
            </View>
          )}
        </View>
        <Loading loading={!listData.length}>
          <AtList>
            {listData.map(({ id, name, artists, ar, al }: any, index) => {
              const activeItem = index === active.index;

              return (
                <AtListItem
                  key={id}
                  title={name}
                  arrow="right"
                  extraText={ar ? this.getArtist(ar) : this.getArtist(artists)}
                  className={activeItem ? "active" : ""}
                  thumb={al?.picUrl}
                  onClick={async () => {
                    const res = await getUrl({ id });

                    innerAudioContext.src = res.data[0].url;
                    // innerAudioContext.startTime = 240;
                    this.setState({
                      active: {
                        index,
                        name,
                        artist: ar
                          ? this.getArtist(ar)
                          : this.getArtist(artists),
                        url: res.data[0].url,
                      },
                    });
                  }}
                />
              );
            })}
          </AtList>
        </Loading>
      </View>
    );
  }
}
